package com.jnu.book;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jnu.book.data.DataBank;
import com.jnu.book.data.book;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookListFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final int RESULT_CODE_ADD_DATA = 996;

    private RecyclerView mainRecyclerView;
    private ArrayList<book> books;
    private BookListFragment.MyRecyclerViewAdapter adapter;
    private DataBank dataBank;
    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;
                String name=data.getStringExtra("name");
                int position=data.getIntExtra("position",books.size());
                books.add(position,new book(name,R.drawable.book_no_name));
                dataBank.saveData();
                adapter.notifyItemInserted(position);

            }
        }
    });
    ActivityResultLauncher<Intent>  launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA) {
                if(null==data)return;
                String name = data.getStringExtra("name");

                int position = data.getIntExtra("position", books.size());
                books.get(position).setTitle(name);
                dataBank.saveData();
                adapter.notifyItemChanged(position);
            }
        }
    });

    // TODO: Rename and change types of parameters


    public BookListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     *
     * @return A new instance of fragment BookListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookListFragment newInstance() {
        BookListFragment fragment = new BookListFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_book_list, container, false);
        initData();
        mainRecyclerView = rootView.findViewById(R.id.recycle_view_books);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new BookListFragment.MyRecyclerViewAdapter(getBooks());
        mainRecyclerView.setAdapter(adapter);
        return rootView;
    }






    protected void initData()
    {
        dataBank=new DataBank(this.getContext());
        books=dataBank.loadData();
    }

    public List<book> getBooks() {
        return books;
    }

    public void setBooks(ArrayList<book> books) {
        this.books = books;
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter{
        private List<book> books;


        public MyRecyclerViewAdapter(List<book> books) {
            this.books=books;
        }
        @NonNull
        //加载视图
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.book_item_holder, parent, false);
            return new BookListFragment.MyRecyclerViewAdapter.MyViewHolder(view);


        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            BookListFragment.MyRecyclerViewAdapter.MyViewHolder holder =(BookListFragment.MyRecyclerViewAdapter.MyViewHolder)Holder;
            holder.getImageView().setImageResource(books.get(position).getCoverResourceId());
            holder.getTextView().setText(books.get(position).getTitle());
        }



        @Override
        public int getItemCount() {
            return books.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener, View.OnClickListener {
            public static final int CONTEXT_MENU_ID_ADD = 1;
            public static final int CONTEXT_MENU_ID_EDIT = 2;
            public static final int CONTEXT_MENU_ID_DELETE = 3;
            private final ImageView imageView;
            private final TextView textView;




            public MyViewHolder(View view) {
                super(view);

                this.imageView=view.findViewById(R.id.image_view_book_cover);
                this.textView=view.findViewById(R.id.text_view_book_title);
                view.setOnClickListener(this);
                view.setOnCreateContextMenuListener(this);

            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextView() {
                return textView;
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                MenuItem addItem=menu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD,"新建");
                MenuItem editItem=menu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT, "修改");
                MenuItem deleteItem =menu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE,"删除");
                addItem.setOnMenuItemClickListener(this);
                editItem.setOnMenuItemClickListener(this);
                deleteItem.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int position = getAdapterPosition();
                LayoutInflater li = LayoutInflater.from(BookListFragment.this.getContext());
                View promptsView = li.inflate(R.layout.input_item, null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        BookListFragment.this.getContext());

                alertDialogBuilder.setView(promptsView);
                AlertDialog alertDialog;

                Intent intent;
                switch(item.getItemId())
                {

                    case CONTEXT_MENU_ID_ADD:
                        intent=new Intent(BookListFragment.this.getContext(), EditBookActivity.class);
                        intent.putExtra("position",position);
                        launcherAdd.launch(intent);

                        break;
                    case CONTEXT_MENU_ID_EDIT:
                        intent=new Intent(BookListFragment.this.getContext(), EditBookActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("name",books.get(position).getTitle());
                        launcherEdit.launch(intent);


                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        View deleteView =li.inflate(R.layout.delete_comfirm,null);
                        alertDialogBuilder.setView(deleteView);
                        alertDialogBuilder
                                .setCancelable(false)
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        books.remove(position);
                                        dataBank.saveData();
                                        BookListFragment.MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                                    }
                                })
                                .setNegativeButton("Cancel",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int id) {
                                                dialog.cancel();
                                            }
                                        });

                        // create alert dialog
                        alertDialog= alertDialogBuilder.create();
                        // show it
                        alertDialog.show();

                        break;
                }
                //Toast.makeText(BookListFragment.this.getContext().this,"点击了"+item.getTitle(), Toast.LENGTH_SHORT).show();
                return false;
            }


            @Override
            public void onClick(View v) {
                Intent intent=new Intent(BookListFragment.this.getContext(), EditBookActivity.class);
                intent.putExtra("position",getAdapterPosition());
                intent.putExtra("name",books.get(getAdapterPosition()).getTitle());
                launcherEdit.launch(intent);
            }
        }
    }
}